package com.changgou.system.filter;

import com.changgou.system.util.JwtUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //2获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //3,判断当前的请求是否是登陆请求,如果是就直接放行
       if( request.getURI().getPath().contains("/admin/login")){
           return chain.filter(exchange);
       }
    
        //4,获取当前的所有请求头信息
        HttpHeaders httpHeaders = request.getHeaders();
        //5,获取jwt令牌信息
        String jwttoken = httpHeaders.getFirst("token");
        //6,判断当前令牌是否存在,如果不存在就向客户端返回错误提示信息
        if (StringUtils.isEmpty(jwttoken)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);//响应中放入返回的状态码,没有权限访问
            return response.setComplete();
        }
        //如果请求头中有令牌则解析令牌
        try {
            JwtUtil.parseJWT(jwttoken);
        } catch (Exception e) {
            e.printStackTrace();
            //解析jwt令牌出错的话,说明令牌过期或者伪造等不合法情况出现
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //放行
        return chain.filter(exchange);
    }
    /*也就是当登录成功后会返回给客户端令牌，需要拿着这个令牌去访问(也就是请求头中携带令牌去访问)，
    解析令牌正确了才能访问具体服务成功。即使有令牌，令牌是错的也会返回错误。*/

    @Override
    public int getOrder() {
        return 0;
    }
}
